package com.platform.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class KuaiDiUtils {
    public static void main(String[] args) throws IOException {


        String host = "https://wuliu.market.alicloudapi.com";
        String path = "/kdi";
        String appcode = "c335c963a09f4afcbdf645273c2536bf";
        String no = "780098068058";
        String type = "zto";
        String urlSend = host + path + "?no=" + no + "&type=" + type;
        URL url = new URL(urlSend);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestProperty("Authorization", "APPCODE " + appcode);
        String json = read(httpURLConnection.getInputStream());
    }

    public static List getOrderTracesByJson(String expCode, String expNo) {
        List<Map<String, Object>> resultObj = new ArrayList<>();
        String host = "https://wuliu.market.alicloudapi.com";
        String path = "/kdi";
        String appcode = "c335c963a09f4afcbdf645273c2536bf";
        String urlSend = host + path + "?no=" + expNo + "&type=" + expCode;

        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestProperty("Authorization", "APPCODE " + appcode);
            String json = read(httpURLConnection.getInputStream());
            JSONObject jsonObject = (JSONObject) JSONObject.parse(json);
            if (null != jsonObject) {
                JSONObject result = jsonObject.getJSONObject("result");
                JSONArray objects = result.getJSONArray("list");
                for (Object obj : objects) {
                    JSONObject jsonObj = (JSONObject) obj;
                    Map<String, Object> temp = new HashMap<>();
                    temp.put("AcceptTime", jsonObj.getString("time"));
                    temp.put("AcceptStation", jsonObj.getString("status"));
                    resultObj.add(temp);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return resultObj;
    }

    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }
}
